<?php
namespace haibao\classlibrary\cms\common;

class Article{
	private static $pageTagCount = 10;
	private static $maxLength = 0;
	private $pageTagArr = array();
	private static $keyData = array();
	private $matchTag = array();
	private $commandStartStr = '<';
	private $commandEndStr = '>';
	private static $picPage = 1;
	private static $domainName = 'www';
	private static $publishId=1;
	private static $isPriview=false;
	public function __construct(){
		if(!self::$keyData){
			$tagInfos = $this->getKey ();
			$maxLength = 0;
			$data = array();
			if($tagInfos){
    			foreach ( $tagInfos as $key => $value ) {
    				$data[$value ['keyword']] = $value;
    				$keyLength = strlen ( $value ['keyword'] );
    				if ($keyLength > $maxLength) {
    					$maxLength = $keyLength;
    				}
    			}
			}
			self::$maxLength = $maxLength;
			self::$keyData = $data;
		}
	}
	
	private static $cmsDomain = '';
	private static $cmsPath = '';
	private static $cdnNewHost = array();
	private static $cdnHost = array();
	
	public static function setCmsDomainAndPath($domain,$path){
		self::$cmsDomain = $domain;
		self::$cmsPath = $path;
	}
	
	public static function getCmsDomain(){
		return self::$cmsDomain ? self::$cmsDomain : \haibao\frame\http\HttpEnvironment::domain();
	}
	
	public static function getCmsPath(){
		return self::$cmsPath ? self::$cmsPath : \haibao\frame\http\HttpEnvironment::path();
	}
	
	public static function setCdnHost($newHost,$oldHost){
		self::$cdnNewHost = $newHost;
		self::$cdnHost = $oldHost;
	}
	
	/**
	 * 替换内容中包含标签的文字为链接
	 */
	public function replaceTagsLink($articleContent){
		$articleContent = str_replace ( '&nbsp;', ' ', $articleContent );
		$articleContent = str_replace ( '&amp;', '&', $articleContent );
		$articleContent = str_replace ( '<br />', '<br>', $articleContent );
	
		$articleContent = $this->format_ch_str($articleContent);
		
		return $this->dealStr($articleContent);
	}

	/**
	 * 图片替换成cdn的链接
	 * @param unknown_type $articleContent
	 */
	public function replaceCDNLink($articleContent){
		$key = \haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_IMG_ENCRYPT_KEY);
		$pattern = "/(<img.*?src=\"(.*?)\".*?>)/is";
		$result = preg_match_all($pattern,$articleContent,$matches);
		if($result){
			$imageUrlArr = $matches[count($matches)-1];
			foreach ($imageUrlArr as $k=>$val){
				$newImgName = md5($val.$key);
				$hasCount =  strpos($val, \haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_STATIC_DOMAIN).'/img');
				if(!is_bool($hasCount)){
					$cdnNum = $this->getHash($newImgName);
					$imgUrl = self::$cdnNewHost[$cdnNum];
					if( \haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_CDN_DEFAULT) ){
						$articleContent =  str_replace(\haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_STATIC_DOMAIN).'/img', $imgUrl, $articleContent);
					}
				} else {
					$hasCount = strpos($val, \haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_HOST_IMAGE));
					if(!is_bool($hasCount)){
						$cdnNum = $this->getHash($newImgName,false);
						$imgUrl = self::$cdnHost[$cdnNum].'/';
						if( \haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_CDN_DEFAULT) ){
							$articleContent =  str_replace(\haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_HOST_IMAGE), $imgUrl, $articleContent);
						}
					}else{
						// TODO : 解决老数据
					    if(preg_match('/http\:\/\/mt0\.haibao\.tv\.*+/isU',$val,$dataArr)){
					        if(isset($dataArr[0]) && $dataArr[0]){
					            if (preg_match ('/((\/piccommon|\/bigfiles|\/product|\/temp|\/blogimages|\/post|\/meijus).*)(\.jpg|\.png|\.gif|\.jpeg|\.bmp)$/i', $val, $relPartData )) {
					                if(isset($relPartData[0]) && $relPartData[0]){
					                    $urlName = substr ( $relPartData[0], strrpos ( $relPartData[0], '/' ) + 1, strlen ( $relPartData[0] ) );
					                    $urlPath = substr ( $relPartData[0], 1, strrpos ( $relPartData[0], '/' ));
					                    if ($urlName && $urlPath) {
				                            $finalUrl = $this->replaceImageLink($urlPath.$urlName,600,0,100,0);
					                    }
					                }
					            }
					        }
					        $cdnNum = $this->getHash($newImgName,false);
					        $imgUrl = self::$cdnNewHost[$cdnNum];
					        $finalUrl =  str_replace(\haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_STATIC_DOMAIN).'/img', $imgUrl, $finalUrl);
					        $articleContent = str_replace($val,$finalUrl , $articleContent);
					    }elseif (preg_match('/https?\:\/\/www\.celebrity\-gossip\.net\.*+/i',$val,$dataArr)){
					        $imgUrl = "http://c1.haibao.cn/img/600_600_100_0/1467282753.5971/b4c1e233d5a6f6314e679fee8e570047.jpg";
					        $articleContent = str_replace($val,$imgUrl , $articleContent);
					    }else{
					        $finalUrl = $this->replaceOldCDN($val);
					        if($finalUrl){
					            if( \haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_CDN_DEFAULT) ){
					                $cdnNum = $this->getHash($newImgName,false);
					                $imgUrl = self::$cdnNewHost[$cdnNum];
					                $finalUrl =  str_replace(\haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_STATIC_DOMAIN).'/img', $imgUrl, $finalUrl);
					            }
					            $articleContent = str_replace($val,$finalUrl , $articleContent);
					        }
					    }
					}
				}
			}
		}
        return $articleContent;
	}
	
	public function replaceImgUrlCDNLink($staticUrl){
		if(!\haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_CDN_DEFAULT)){
			return $staticUrl;
		}
		$key = \haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_IMG_ENCRYPT_KEY);
		$newImgName = md5($staticUrl.$key);
		$hasCount = strpos($staticUrl, \haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_STATIC_DOMAIN).'/img');
		$cdnUrl = "";
		if(!is_bool($hasCount)){
			$cdnNum = $this->getHash($newImgName);
			$imgUrl = self::$cdnNewHost[$cdnNum];
			$cdnUrl =  str_replace(\haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_STATIC_DOMAIN).'/img', $imgUrl, $staticUrl);
		} else {
			
			$hasCount = strpos($staticUrl, \haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_HOST_IMAGE));
			if(!is_bool($hasCount)){
				$cdnNum = $this->getHash($newImgName,false);
				$imgUrl = self::$cdnHost[$cdnNum];
				$cdnUrl =  str_replace(\haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_HOST_IMAGE), $imgUrl, $staticUrl);
			}else{
				// TODO : 解决老数据
				$finalUrl = $this->replaceOldCDN($staticUrl);
				if($finalUrl){
					$articleContent = str_replace($staticUrl,$finalUrl , $articleContent);
				}
			}
		}
		return $cdnUrl;
	}
	/**
	 * 图片替换成static的链接
	 * @param string $imgUrl
	 * @param int $width	宽 600(文章图片最大为600)
	 * @param int $height	高
	 * @param int $quality	质量(0-100)，默认75
	 * @param int $water	是否水印(1打0无)
	 * @return string
	 */
	public function replaceImageLink($imgUrl,$width = 600,$height = 0,$quality = 100,$water = 1){	
        $key = \haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_IMG_ENCRYPT_KEY);
        $imgFileName = substr($imgUrl, strrpos($imgUrl, '/')+1);
        $imgName = substr($imgFileName, 0, strrpos($imgFileName, '.'));
        $imgType = substr($imgFileName, strrpos($imgFileName, '.'));
        $condition = '/'.$width.'_'.$height.'_'.$quality.'_'.$water.'/'.$imgName.'/';
        $newUrl = '';
        $isHasUploads = strpos($imgUrl, \haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::IMAGE_UPLOAD_BASE_PATH));
        if($isHasUploads === false){
        	$newImgName = str_replace(self::$cmsDomain, '', $imgUrl);
        	$newUrl = \haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_STATIC_DOMAIN).'/img'.$condition.$newImgName;
        } else {
       		$newImgName = md5($condition.$key);      
       		$newUrl = \haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_STATIC_DOMAIN).'/img'.$condition.$newImgName.$imgType;
        }
        return $newUrl;
    }
    
    public function setImageLink($articleContent,$publishId,$isPriview = false,$picPage=1,$domaiName = 'www'){
    	self::$picPage = $picPage;
    	self::$publishId = $publishId;
    	self::$isPriview = $isPriview;
    	self::$domainName = $domaiName;
    	$pattern = "/(<img (?!videosrc).*?src=\"(.*?)\".*?>)/is";

    	$articleContent = preg_replace_callback($pattern,'self::replaceImageUrlToPic',$articleContent);
    	return array($articleContent,self::$picPage);
        /* if($result){
        	$target ="";
            $pageNext = $currentPage + 1;
            $articleViewName = \haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::NEW_ARTICLE_VIEW_NAME);
            $url = $articleViewName.$articleId.'_'.$pageNext.'.htm';
            if($isPriview){
            	$url = '/article/priview.html?id='.$articleId.'&page='.$pageNext.'&type=1';
            } else {
            	$articleBusiness = new ArticleBusiness ();
            	$articleIdArr = $articleBusiness->getOldAticleId(array($articleId));
            	if(!$publishId){
            		$publishId = $articleId;
            		if(!empty($articleIdArr[$articleId])){
            			$publishId = $articleIdArr[$articleId];
            		}
            	}	
            	$url = $articleViewName.$publishId.'_'.$pageNext.'.htm';
            }
            //最后一页打下一篇文章的链接
            if($totlaPage == $currentPage) {
                $url = $nextArticleUrl;
                $target = " target='_blank' ";
            }
            if(empty($url)){
            	$url = 'javascript:;';
            	$target = '';
            }
           $replacement = "<a ".$target." href=\"".$url."\">$1</a>";
           $articleContent = preg_replace($pattern, $replacement, $articleContent);
        }*/
    }
	
    private static function replaceImageUrlToPic($matches){
    	
    	$html = '';
    	if(isset($matches[0])){
    		$imageHtml = $matches[0];
    		if(self::$isPriview){
    			$picArticleUrl = \haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_HOST_PIC);
    		}else{
    		   	self::$picPage = self::$picPage+1;
    		    if(	self::$picPage==1){
    		        $picArticleUrl = \haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_HOST_PIC).'/'.self::$domainName.'/article/'.self::$publishId.'.htm';
    		    }else{
    		        $picArticleUrl = \haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_HOST_PIC).'/'.self::$domainName.'/article/'.self::$publishId.'.'.self::$picPage.'.htm';
    		    }
    			//$picArticleUrl = \haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_HOST_PIC).'/'.self::$domainName.'/article/'.self::$publishId.'.htm?page='.self::$picPage;
    		    
    			$html = "<a target='_blank' href=\"".$picArticleUrl."\">$imageHtml</a>";;
    		}
    	}
    	//self::$picPage = self::$picPage+1;
    	return $html;
    }
	private function getKey() {
		$ret_key_row = array();
		
		$filename = self::$cmsPath.'/web/common/key_words.php';
		if(file_exists($filename)){
		  include $filename;
		  return $ret_key_row;
	   }
	}

	private function format_ch_str($str) {
		$str = htmlspecialchars_decode($str);
		//要替换的数据源
		$r1 = array('&ldquo;','&rdquo;','&lsquo;','&rsquo;','&hellip;','&amp;','&#39;','&mdash;','&middot;');
		//替换成的东东
		$r2 = array('“','”','‘','’','…','&','\'','—','·');
		return str_replace($r1,$r2,$str);
	}
	
	private function dealStr($articleContent){
		$strStart = 0;
		$length = strlen ( $articleContent );
		$newArticleContent = '';
		while ( $strStart < $length ) {
			$appendContent = $this->findContent ( $articleContent,$this->commandStartStr,$strStart );
			$newArticleContent .= $this->dealContentVoid ( $appendContent, self::$maxLength );
			if ($strStart < $length){
				$startCommandLength = strlen($this->commandStartStr);
				$tagStartPos = $strStart + $startCommandLength;
				$tag = $this->getTagName($articleContent,$tagStartPos);
				$tagLength = strlen($tag);
				//没有匹配到标签名
				if ($tagStartPos >= $length){
					$appendContent = substr($articleContent, $strStart , $length - $strStart);
					$newArticleContent .= $this->dealContentVoid($appendContent,self::$maxLength);
					$strStart = $length;
				}else{
					$tagLow = strtolower($tag);
					$tagLength = strlen($tagLow);
					$tagEndPos = $tagStartPos;
					$this->findContent($articleContent,$this->commandEndStr,$tagEndPos);
					//未找到结束标记">"
					if ($tagEndPos >= $length){
						$appendContent = substr($articleContent,$strStart,$length - $strStart);
						$newArticleContent .= $this->dealContentVoid($appendContent,self::$maxLength);
						$strStart = $length;
					}else{
						$endTag = '</'.$tagLow.'>';
						$endTagLength = strlen($endTag);
						$endContentPos = $tagEndPos + strlen($this->commandEndStr);
						$this->findEndTag($articleContent,$tagLow,$endContentPos);
							
						//未找到结束标签</tagName>
						if ($endContentPos >= $length){
							$tagClose = '/>';
							$tagClosePos = $tagStartPos;
							$this->findContent($articleContent,$tagClose,$tagClosePos);
							if ($tagClosePos >= $length){
								$appendContent = substr($articleContent,$strStart,$startCommandLength);
								$strStart += $startCommandLength;
							}else{
								$appendContent = substr($articleContent,$strStart,$tagClosePos + strlen($tagClose) - $strStart);
								$strStart = $tagClosePos + strlen($tagClose);
							}
							$newArticleContent .= $appendContent;
							/* if(!stristr($newArticleContent, "embed")){
								$newArticleContent .= $appendContent;
							} */
						}else{
							//找到标签
							//标签内的内容不处理
							$newArticleContent .= substr($articleContent, $strStart , $tagEndPos - $strStart + 1);
							$innerContent = substr($articleContent , $tagEndPos + 1 , $endContentPos-$tagEndPos-1);
							//如标签是 a,style,script 内容不处理
							if ($tagLow == 'a' || $tagLow == 'style' || $tagLow == 'script'){
								$newArticleContent .= $innerContent;
							}else{
								$newArticleContent .= $this->dealStr($innerContent);
							}
	
							$newArticleContent .= substr($articleContent, $endContentPos,$endTagLength);
							$strStart = $endContentPos + $endTagLength;
						}
					}
				}
			}
		}
		return $newArticleContent;
	}
	
	private function findContent($content, $commandStr, &$strStart) {
		$articleContent = '';
		$step = strlen ($commandStr);
		$length = strlen ( $content );
		while ( true ) {
			if ($strStart >= $length) {
				$strStart = $length;
				break;
			}
			if ($strStart + $step > $length) {
				$articleContent .= substr ( $content, $strStart, $length - $strStart );
				$strStart = $length;
				break;
			}
			$s = substr ( $content, $strStart, $step );
			if ($s == $commandStr) {
				break;
			} else {
				$articleContent .= substr ( $content, $strStart, 1 );
				$strStart ++;
			}
		}
		return $articleContent;
	}
	
	private function findEndTag($content,$tagName,&$strStart){
		$articleContent = '';
		$str = '</'.$tagName.'>';
		$step = strlen($str);
		$length = strlen($content);
		$startPos = $strStart;
		$tagStart = '<'.$tagName;
	
		while(true){
			if ($strStart >= $length){
				$strStart = $length;
				break;
			}
			if ($strStart + $step > $length){
				$articleContent .= substr($content,$strStart,$length-$strStart);
				$strStart = $length;
				break;
			}
			$s = substr($content,$strStart,$step);
			if ($s == $str){
				//检查嵌套标签
				//嵌套标签不出现或者成对出现
				$innerContent = substr($content,$startPos,$strStart-$startPos);
				$startCount = substr_count($innerContent, $tagStart);
				$endCount = substr_count($innerContent, $str);
	
				if (!$startCount ||	$startCount == $endCount){
					break;
				}else{
					$strStart++;
				}
			}else{
				$articleContent .= substr($content,$strStart,1);
				$strStart++;
			}
		}
		return $articleContent;
	}
	
	private function getTagName($text,&$strStart){
		$tagName = '';
		$length = strlen($text);
	
		while(true){
			if ($strStart >= $length){
				$strStart = $length;
				break;
			}
			$s = substr($text,$strStart,1);
	
			if ($s == '>' || $s == ' '){
				break;
			}else if ($tagName == '' && $s == '/'){
				$strStart++;
			}else{
				$tagName .= $s;
				$strStart++;
			}
		}
		return $tagName;
	}
	
	private function dealContentVoid($articleContent, $matchLength) {
		$str = '';
		$articleContentLength = strlen ( $articleContent );
		if (! $matchLength) {
			$str .= $articleContent;
			return $str;
		}
	
		if ($articleContentLength < $matchLength) {
			$str .= $this->dealContentVoid ( $articleContent, $matchLength - 1 );
			return $str;
		}
		$matched = false;
		for($i = 0; $i <= $articleContentLength - $matchLength; $i ++) {
			$part = substr ( $articleContent, $i, $matchLength );
			if (!empty ( self::$keyData[$part] )) {
				$matched = true;
				if ($i > 0) {
					$str .= $this->dealContentVoid ( substr ( $articleContent, 0, $i ), $matchLength - 1 );
				}
	
				//打标签计数
				if(!empty($this->pageTagArr[self::$keyData[$part]['tag_id']])){
					if($this->pageTagArr[self::$keyData[$part]['tag_id']] <= self::$pageTagCount){
						$this->pageTagArr[self::$keyData[$part]['tag_id']] = $this->pageTagArr[self::$keyData[$part]['tag_id']] + 1;
					}else{
						$this->pageTagArr[self::$keyData[$part]['tag_id']] = 1;
					}
				}else{
					$this->pageTagArr[self::$keyData[$part]['tag_id']] = 1;
				}
				if($this->pageTagArr[self::$keyData[$part]['tag_id']] == 1){
					$link = self::$keyData [$part] ['link'];
					$str .= '<a class="ngaryd" href="' . $link . '" target="_blank">' . $part . '</a>';
				} else {
					$str .= $part;
				}
				
				$str .= $this->dealContentVoid ( substr ( $articleContent, ($i + $matchLength), ($articleContentLength - $i - $matchLength) ), $matchLength );
				break;
			}
		}
	
		if (! $matched) {
			$str .= $this->dealContentVoid ( $articleContent, $matchLength - 1 );
		}
	
		return $str;
	}
    public function getHash($key,$isNew = true){
    	$hash = crc32($key) >> 16 & 0xffff;
    	$cdnHostArr = self::$cdnNewHost;
    	if(!$isNew){
    		$cdnHostArr = self::$cdnHost;
    	}
    	return sprintf('%01s',$hash % count($cdnHostArr));
    }
    /**
     * 根据文本内容匹配标签（非文章内容）
     */
    public function matchTagByText($text){
    	$maxLength = 1;
    	if(empty(self::$keyData)){
    		$tagInfos = $this->getKey ();
    		foreach ( $tagInfos as $key => $value ) {
    			self::$keyData [$value ['keyword']] = $value;
    			$keyLength = strlen ( $value ['keyword'] );
    			if ($keyLength > $maxLength) {
    				$maxLength = $keyLength;
    			}
    		}
    	}else{
    		$maxLength = self::$maxLength;
    	}
    	$this->dealText($text, $maxLength);
    	return $this->matchTag;
    }
    
    private function dealText($text, $matchLength) {
    	$str = '';
    	$articleContentLength = strlen ( $text );
    	if (! $matchLength) {
    		$str .= $text;
    		return $str;
    	}
    
    	if ($articleContentLength < $matchLength) {
    		$str .= $this->dealText ( $text, $matchLength - 1 );
    		return $str;
    	}
    
    	$matched = false;
    	for($i = 0; $i <= $articleContentLength - $matchLength; $i ++) {
    		$part = substr ( $text, $i, $matchLength );
    		if (isset ( self::$keyData [$part] )) {
    			$matched = true;
    			if ($i > 0) {
    				$str .= $this->dealText ( substr ( $text, 0, $i ), $matchLength - 1 );
    			}
    
    			//打标签计数
    			if(!empty($this->pageTagArr[self::$keyData[$part]['tag_id']])){
    				if($this->pageTagArr[self::$keyData[$part]['tag_id']] <= self::$pageTagCount){
    					$this->pageTagArr[self::$keyData[$part]['tag_id']] = $this->pageTagArr[self::$keyData[$part]['tag_id']] + 1;
    				}else{
    					$this->pageTagArr[self::$keyData[$part]['tag_id']] = 1;
    				}
    			}else{
    				$this->pageTagArr[self::$keyData[$part]['tag_id']] = 1;
    			}
    			
    			if($this->pageTagArr[self::$keyData[$part]['tag_id']] == 1){
    				$this->matchTag[self::$keyData[$part]['tag_id']] = $part;
    			} else {
    				$str .= $part;
    			}
    
    			$str .= $this->dealText ( substr ( $text, ($i + $matchLength), ($articleContentLength - $i - $matchLength) ), $matchLength );
    			break;
    		}
    	}
    
    	if (! $matched) {
    		$str .= $this->dealText ( $text, $matchLength - 1 );
    	}
    }
    
    private static $xorkeys = array(185,76,239,141,221,242,170,131,179,198,251,246,125,158,176,200,228,
    		178,24,193,200,177,47,81,207,155,122,77,5,182,249,254,141,108,233,
    		187,251,63,241,33,115,151,2,166,19,239,104,212,110,232,87,175,235,
    		31,125,196,31,187,218,255,74,173,74,24,79,22,157,92,132,91,50,97,
    		142,3,50,7,165,238,41,114,76,122,141,121,189,193,127,60,176,217,232,
    		149,5,179,116,127,174,190,13,246,102,109,18,85,48,54,112,196,244,116,
    		174,209,32,150,0,173,57,57,252,49,62,145,60,46,45,9,165,92,168,211,
    		137,240,210,154,199,46,36,153,14,106,29,111,166,69,60,243,207,77,216,
    		55,39,18,92,196,100,109,5,189,156,208,42,31,166,70,200,223,110,150,47,
    		118,46,89,41,216,70,87,156,30,136,86,139,79,76,65,141,23,109,214,107,
    		24,140,171,61,151,233,150,152,234,80,104,149,82,214,248,116,179,178,
    		56,164,124,78,16,189,202,38,148,88,38,146,253,176,6,232,27,27,203,172,
    		168,41,250,76,247,130,216,15,126,117,210,8,142,133,25,194,166,34,10,
    		34,107,93,43,10,209,81,93,123);
    
    //十六进制 转 ASCII
    private static function hex2asc($str) {
    	$data = '';
    	$len = strlen($str);
    	for ($i=0; $i<$len; $i+=2) $data .= chr(hexdec(substr($str, $i, 2)));
    	return $data;
    }
    //加密,参数：文件名
    public static function qencrypt($name){
    	$result="";
    	for($i=0; $i<strlen($name); $i++){
    		$result .= chr(ord($name[$i]) ^ self::$xorkeys[$i]);
    	}
    	return strtoupper(bin2hex($result));
    }
    //解密,参数：文件名
    public static function qdecrypt($name){
    	$s = self::hex2asc($name);
    	$result="";
    	for($i=0; $i<strlen($s); $i++){
    		$result .= chr ( ord ( $s [$i] ) ^ self::$xorkeys [$i] );
		}
		return $result;
	}
	public function replaceOldCDN($url) {
		$finalUrl = '';
		if (preg_match ( '/((\/bigfiles|\/piccommon|\/meiju|\/product|\/temp|\/blogimages|\/post|\/meijus).*)(\.jpg|\.png|\.gif|\.jpeg|\.bmp)$/i', $url, $match )) {
			$sourceUrl = $match [1];
			$urlName = substr ( $sourceUrl, strrpos ( $sourceUrl, '/' ) + 1, strlen ( $sourceUrl ) );
			$urlPath = substr ( $sourceUrl, 1, strrpos ( $sourceUrl, '/' ));
			if ($urlName && $urlPath) {
				if(!strpos($urlName,'.')){
					$sourceName = self::qdecrypt($urlName).$match[3];
					if($sourceName){
						$finalUrl = $this->replaceImageLink($urlPath.$sourceName,600,0,100,0);
						
					}
				}else{
					$finalUrl = $this->replaceImageLink($urlPath.$urlName.$match[3],600,0,100,0);
				}
			}
		}
    	return $finalUrl;
    }
}